<template>
  <n-modal
    v-model:show="visible"
    :title="title"
    preset="dialog"
    transform-origin="center"
    :mask-closable="false"
    :show-icon="false"
    :positive-text="props.submitText"
    :negative-text="props.cancelText"
    @positive-click="handlePositiveClick"
    @negative-click="handleNegativeClick"
    @update:show="evt => emit('update:show', evt)"
  >
    <ie-form
      v-bind="props"
      ref="formRef"
    />
  </n-modal>
</template>

<script setup>
import { ref, watch } from 'vue'
import { formPropsDefine } from './IeForm.vue'

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: ''
  },
  initFormValue: {
    type: Object,
    default: () => ({})
  },
  submitText: {
    type: String,
    default: '确定'
  },
  cancelText: {
    type: String,
    default: '取消'
  },
  onSubmit: {
    type: Function,
    default: () => {}
  },
  onCancel: {
    type: Function,
    default: () => {}
  },
  ...formPropsDefine
})

const emit = defineEmits([
  'update:show',
  'submit',
  'cancel'
])

const visible = ref(false)
const formRef = ref()

watch(
  () => props.show,
  show => visible.value = show, {
    immediate: true
  }
)

watch(
  () => formRef.value,
  formRefValue => {
    if (formRefValue && Object.keys(props.initFormValue).length) {
      formRefValue?.set(props.initFormValue)
    }
  }, { immediate: true }
)

const close = () => emit('update:show', visible.value = false)

function handlePositiveClick() {
  if (formRef.value) {
    formRef.value.submit().then(values => {
      emit('submit', values, close)
    })
  }

  return false
}

function handleNegativeClick() {
  emit('cancel', close)
}
</script>